<!-- 本页面是dialog对话框 -->

<script setup>
import { ref } from 'vue'
import { artEditChannelService, artAddChannelService } from '@/api/article.js'

//el-dialog组件的数据初始化
const dialogVisible = ref(false)
const formRef = ref() //初始化数据
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})

//校验规则
const rules = {
  cate_name: [
    { required: true, message: '分类名称不能为空', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '分类别名不能为空', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类名必须是1-15位的字母或数字',
      trigger: 'blur'
    }
  ]
}
//通过defineEmits编译宏，生成emit方法
const emit = defineEmits(['success'])
//提交事件
const onSubmit = async () => {
  await formRef.value.validate() //通过校验才会继续往下执行
  const isEdit = formModel.value.id
  if (isEdit) {
    await artEditChannelService(formModel.value)
    ElMessage.success('编辑成功')
  } else {
    await artAddChannelService(formModel.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  //通知页面更新页面
  emit('success')
}

//本组件没有对外暴露任何的东西---→外部改变不了当前的内容
//组件对外暴露一个方法 open,基于open传来的参数，区分添加还是编辑
//open({}) ==>表单无需渲染，说明是添加
//open({id,cate_name,...})=> 表单需要渲染，说明是编辑
//open调用后，可以打开弹窗

const open = (row) => {
  //console.log(row)
  dialogVisible.value = true
  //将传过来的row赋值给
  formModel.value = { ...row } //添加--→重置了表单内容，编辑--→存储了需要回显的数据
}
//向组件外暴露方法
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="500"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          v-model="formModel.cate_name"
          placeholder="请输入分类名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input
          v-model="formModel.cate_alias"
          placeholder="请输入分类别名"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
